package com.im.redis;

import cn.hutool.json.JSONUtil;
import com.im.entity.MessageEntity;
import com.im.util.RedisUtil;
import com.im.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * cmd 操作反射执行 HttpAuthHandler.handleTextMessage方法下的  cmd
 */
@Slf4j
@Component
public class AppMessage {
    /**
     * 发送消息
     */
    public void sendMessage(String payload, WebSocketSession session) throws IOException {
        MessageEntity message = JSONUtil.toBean(payload, MessageEntity.class);
        Object fromId = session.getAttributes().get("id");
        //发送消息
        WebSocketSession fromSession = SessionUtil.get(fromId.toString());
        //发送自己
        fromSession.sendMessage(new TextMessage(  "我: " + message.getContent()));
        //发送对方
        WebSocketSession toSession = SessionUtil.get(message.getToId());
        if(null != toSession){
            toSession.sendMessage(new TextMessage(fromId + ": " + message.getContent()));
        }else{
            //校验是否在线
            Object o = RedisUtil.get(RedisPatternTopic.session + message.getToId());
            if(null == o){
                //不在线直接发送离线
                SessionUtil.readMsg(message.getToId(),fromId + ": " + message.getContent());
                return;
            }
            MessageEntity map = new MessageEntity();
            map.setToId(message.getToId());
            map.setContent(fromId + ": " + message.getContent());
            System.out.println("obj" +JSONUtil.toJsonStr(map));
            RedisUtil.convertAndSend(RedisPatternTopic.PATTERN_TOPIC,JSONUtil.toJsonStr(map));
        }
    }

}
